package com.jqkb.pages;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.fasterxml.jackson.databind.JsonNode;
import com.jqkb.R;
import com.jqkb.service.UserService;
import com.jqkb.service.util.CallBack;
import com.jqkb.service.util.Converter;
import com.jqkb.service.util.SimpleApi;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Call;

public class ChangePassActivity extends AppCompatActivity {

    private EditText pass1Edt;
    private EditText pass2Edt;
    private EditText oldPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_password_activity);
        pass1Edt = ((EditText) findViewById(R.id.pass1Edt));
        pass2Edt = ((EditText) findViewById(R.id.pass2Edt));
        oldPassword = ((EditText) findViewById(R.id.oldPassword));

    }

    public void change(View view) {
        String oldPassword = this.oldPassword.getText().toString();
        String password1 = pass1Edt.getText().toString();
        String password2 = pass2Edt.getText().toString();
        if (StringUtils.isEmpty(password1)) {
            Toast.makeText(this, "新密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!StringUtils.equals(password1, password2)) {
            Toast.makeText(this, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }


        UserService userService = SimpleApi.create(UserService.class);
        Call<ResponseBody> responseBodyCall = userService.changePassword(oldPassword, password1);
        Converter.convert(Object.class, responseBodyCall, new CallBack<Object>() {
            @Override
            public void onSuccess(Object object, JsonNode data) {
                Toast.makeText(ChangePassActivity.this, data.path("message").asText("操作成功"), Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFail(boolean success, int code, String message, JsonNode data) {
                Toast.makeText(ChangePassActivity.this, message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNetworkFail(Call<ResponseBody> jsonNode) {
                Toast.makeText(ChangePassActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Call<ResponseBody> response) {
                Toast.makeText(ChangePassActivity.this, "发生意外错误", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
